<template>
  <div class="sheep-inventory-container">
    <div class="inventory-header">
      <h2>羊场存栏统计</h2>
      <div class="header-actions">
        <button @click="refreshData" class="refresh-btn">刷新数据</button>
        <div class="export-group">
          <select v-model="exportFormat" class="export-format-select">
            <option value="excel">Excel格式</option>
            <option value="csv">CSV格式</option>
          </select>
          <button @click="exportData" class="export-btn">导出报表</button>
        </div>
      </div>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <div class="filter-row">
        <div class="filter-item">
          <label>羊场选择：</label>
          <select v-model="filterParams.farmId" @change="handleFilterChange">
            <option value="">全部羊场</option>
            <option v-for="farm in farms" :key="farm.farmId" :value="farm.farmId">
              {{ farm.farmName }}
            </option>
          </select>
        </div>
        <div class="filter-item">
          <label>开始日期：</label>
          <input 
            type="date" 
            v-model="filterParams.startDate" 
            @change="handleFilterChange"
          />
        </div>
        <div class="filter-item">
          <label>结束日期：</label>
          <input 
            type="date" 
            v-model="filterParams.endDate" 
            @change="handleFilterChange"
          />
        </div>
      </div>
      <div class="filter-actions">
        <button @click="searchData" class="search-btn">查询</button>
        <button @click="resetFilter" class="reset-btn">重置</button>
      </div>
    </div>

    <!-- 统计概览 -->
    <div class="overview-section">
      <div class="overview-card">
        <div class="overview-title">总存栏数</div>
        <div class="overview-value">{{ inventoryData.totalCount || 0 }}</div>
        <div class="overview-unit">只</div>
      </div>
      <div class="overview-card">
        <div class="overview-title">品种数量</div>
        <div class="overview-value">{{ inventoryData.breedStatistics?.length || 0 }}</div>
        <div class="overview-unit">种</div>
      </div>
      <div class="overview-card">
        <div class="overview-title">公羊数量</div>
        <div class="overview-value">{{ maleCount }}</div>
        <div class="overview-unit">只</div>
      </div>
      <div class="overview-card">
        <div class="overview-title">母羊数量</div>
        <div class="overview-value">{{ femaleCount }}</div>
        <div class="overview-unit">只</div>
      </div>
    </div>

    <!-- 图表展示 -->
    <div class="charts-section">
      <div class="chart-container">
        <div class="chart-title">品种分布</div>
        <div class="chart-content">
          <div v-if="inventoryData.breedStatistics && inventoryData.breedStatistics.length > 0" class="breed-list">
            <div 
              v-for="breed in inventoryData.breedStatistics" 
              :key="breed.breed" 
              class="breed-item"
            >
              <div class="breed-name">{{ breed.breed }}</div>
              <div class="breed-bar">
                <div 
                  class="breed-bar-fill" 
                  :style="{ width: breed.percentage + '%' }"
                ></div>
              </div>
              <div class="breed-count">{{ breed.count }}只 ({{ breed.percentage }}%)</div>
            </div>
          </div>
          <div v-else class="no-data">暂无数据</div>
        </div>
      </div>

      <div class="chart-container">
        <div class="chart-title">性别分布</div>
        <div class="chart-content">
          <div class="gender-stats">
            <div class="gender-item">
              <div class="gender-icon male">♂</div>
              <div class="gender-info">
                <div class="gender-label">公羊</div>
                <div class="gender-count">{{ maleCount }}只</div>
              </div>
            </div>
            <div class="gender-item">
              <div class="gender-icon female">♀</div>
              <div class="gender-info">
                <div class="gender-label">母羊</div>
                <div class="gender-count">{{ femaleCount }}只</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 详细数据表格 -->
    <div class="table-section">
      <div class="table-header">
        <h3>详细统计</h3>
        <div class="table-actions">
          <select v-model="tableSortBy" @change="handleSortChange">
            <option value="">默认排序</option>
            <option value="breed">按品种</option>
            <option value="count">按数量</option>
            <option value="percentage">按比例</option>
          </select>
        </div>
      </div>
      
      <div class="table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th>品种</th>
              <th>数量</th>
              <th>比例</th>
              <th>公羊数量</th>
              <th>母羊数量</th>
              <th>平均年龄</th>
              <th>健康状态</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="breed in sortedBreedStatistics" :key="breed.breed">
              <td>{{ breed.breed }}</td>
              <td>{{ breed.count }}</td>
              <td>{{ breed.percentage }}%</td>
              <td>{{ breed.maleCount || 0 }}</td>
              <td>{{ breed.femaleCount || 0 }}</td>
              <td>{{ breed.avgAge || '--' }}</td>
              <td>
                <span :class="getHealthStatusClass(breed.healthStatus)">
                  {{ breed.healthStatus || '正常' }}
                </span>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <div class="loading-text">加载中...</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { api } from '../utis/request'
import toast from '../utils/toast'

// 响应式数据
const loading = ref(false)
const farms = ref<any[]>([])
const inventoryData = ref<any>({})
const tableSortBy = ref('')
const exportFormat = ref('excel')

// 筛选参数
const filterParams = reactive({
  farmId: '',
  startDate: '',
  endDate: ''
})

// 计算属性
const maleCount = computed(() => {
  return inventoryData.value.genderStatistics?.find((g: any) => g.gender === 'Male')?.count || 0
})

const femaleCount = computed(() => {
  return inventoryData.value.genderStatistics?.find((g: any) => g.gender === 'Female')?.count || 0
})

const sortedBreedStatistics = computed(() => {
  if (!inventoryData.value.breedStatistics) return []
  
  const stats = [...inventoryData.value.breedStatistics]
  
  switch (tableSortBy.value) {
    case 'breed':
      return stats.sort((a, b) => a.breed.localeCompare(b.breed))
    case 'count':
      return stats.sort((a, b) => b.count - a.count)
    case 'percentage':
      return stats.sort((a, b) => b.percentage - a.percentage)
    default:
      return stats
  }
})

// 方法
const loadFarms = async () => {
  try {
    const response = await api.sheep.getFarms()
    farms.value = response.data?.data || []
  } catch (error) {
    console.error('加载羊场列表失败:', error)
  }
}

const loadInventoryData = async () => {
  loading.value = true
  try {
    const params: any = {}
    if (filterParams.farmId) params.farmId = filterParams.farmId
    if (filterParams.startDate) params.startDate = filterParams.startDate
    if (filterParams.endDate) params.endDate = filterParams.endDate
    
    const response = await api.sheep.getInventoryStatistics(params)
    inventoryData.value = response.data || {}
  } catch (error) {
    console.error('加载存栏统计数据失败:', error)
  } finally {
    loading.value = false
  }
}

const searchData = () => {
  loadInventoryData()
}

const resetFilter = () => {
  filterParams.farmId = ''
  filterParams.startDate = ''
  filterParams.endDate = ''
  loadInventoryData()
}

const handleFilterChange = () => {
  // 可以在这里添加防抖逻辑
}

const handleSortChange = () => {
  // 排序逻辑在computed中处理
}

const refreshData = () => {
  loadInventoryData()
}

const exportData = async () => {
  try {
    // 显示加载状态
    loading.value = true
    
    // 构建导出参数
    const params: any = {
      format: exportFormat.value // 使用用户选择的格式
    }
    
    // 添加筛选参数
    if (filterParams.farmId) params.farmId = filterParams.farmId
    if (filterParams.startDate) params.startDate = filterParams.startDate
    if (filterParams.endDate) params.endDate = filterParams.endDate
    
    // 调用导出API
    const response = await api.sheep.exportInventoryStatistics(params)
    
    // 创建下载链接
    const isExcel = exportFormat.value === 'excel'
    const blob = new Blob([response.data], { 
      type: isExcel ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' : 'text/csv;charset=utf-8'
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    
    // 生成文件名
    const timestamp = new Date().toISOString().slice(0, 10).replace(/-/g, '')
    const farmName = filterParams.farmId ? 
      farms.value.find(f => f.farmId == filterParams.farmId)?.farmName || '筛选' : 
      '全部'
    const extension = isExcel ? 'xlsx' : 'csv'
    link.download = `羊场存栏统计报表_${farmName}_${timestamp}.${extension}`
    
    // 触发下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    // 清理URL对象
    window.URL.revokeObjectURL(url)
    
    // 显示成功提示
    toast.success('导出成功', '报表已成功导出并开始下载')
    
  } catch (error) {
    console.error('导出报表失败:', error)
    toast.error('导出失败', '报表导出失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const getHealthStatusClass = (status: string) => {
  switch (status) {
    case 'Healthy':
      return 'status-healthy'
    case 'Sick':
      return 'status-sick'
    case 'Quarantined':
      return 'status-quarantined'
    default:
      return 'status-normal'
  }
}

// 生命周期
onMounted(() => {
  loadFarms()
  loadInventoryData()
})
</script>

<style scoped>
.sheep-inventory-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.inventory-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.inventory-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.export-group {
  display: flex;
  gap: 8px;
  align-items: center;
}

.export-format-select {
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  background-color: white;
  cursor: pointer;
}

.refresh-btn, .export-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.refresh-btn {
  background-color: #1890ff;
  color: white;
}

.export-btn {
  background-color: #52c41a;
  color: white;
}

.filter-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.filter-row {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-weight: 500;
  color: #333;
  min-width: 80px;
}

.filter-item select, .filter-item input {
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
}

.filter-actions {
  display: flex;
  gap: 10px;
}

.search-btn, .reset-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.search-btn {
  background-color: #1890ff;
  color: white;
}

.reset-btn {
  background-color: #f5f5f5;
  color: #333;
  border: 1px solid #d9d9d9;
}

.overview-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.overview-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.overview-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.overview-value {
  font-size: 32px;
  font-weight: bold;
  color: #1890ff;
  margin-bottom: 4px;
}

.overview-unit {
  font-size: 12px;
  color: #999;
}

.charts-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.chart-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 15px;
}

.breed-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.breed-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.breed-name {
  min-width: 80px;
  font-size: 14px;
  color: #333;
}

.breed-bar {
  flex: 1;
  height: 20px;
  background-color: #f0f0f0;
  border-radius: 10px;
  overflow: hidden;
}

.breed-bar-fill {
  height: 100%;
  background: linear-gradient(90deg, #1890ff, #52c41a);
  transition: width 0.3s ease;
}

.breed-count {
  min-width: 80px;
  font-size: 12px;
  color: #666;
  text-align: right;
}

.gender-stats {
  display: flex;
  justify-content: space-around;
}

.gender-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.gender-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  font-weight: bold;
}

.gender-icon.male {
  background-color: #1890ff;
  color: white;
}

.gender-icon.female {
  background-color: #eb2f96;
  color: white;
}

.gender-info {
  text-align: left;
}

.gender-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.gender-count {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 0 20px;
}

.table-header h3 {
  margin: 0;
  color: #333;
}

.table-actions select {
  padding: 6px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
}

.table-container {
  padding: 20px;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

.data-table th {
  background-color: #fafafa;
  font-weight: 500;
  color: #333;
}

.data-table tr:hover {
  background-color: #f5f5f5;
}

.status-healthy {
  color: #52c41a;
  font-weight: 500;
}

.status-sick {
  color: #ff4d4f;
  font-weight: 500;
}

.status-quarantined {
  color: #faad14;
  font-weight: 500;
}

.status-normal {
  color: #1890ff;
  font-weight: 500;
}

.no-data {
  text-align: center;
  color: #999;
  padding: 40px;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-text {
  margin-top: 10px;
  color: #666;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@media (max-width: 768px) {
  .charts-section {
    grid-template-columns: 1fr;
  }
  
  .filter-row {
    flex-direction: column;
    gap: 10px;
  }
  
  .overview-section {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style> 